<?php

namespace App\Admin\Grid\Displayers;

class Actions extends AbstractDisplayer
{
    /**
     * 在操作按钮组后面追加的按钮
     *
     * @var array
     */
    protected $appends = [];

    /**
     * 在操作按钮组前面追加的按钮
     *
     * @var array
     */
    protected $prepends = [];

    /**
     * 允许编辑
     *
     * @var bool
     */
    protected $allowEdit = true;

    /**
     * 允许删除
     *
     * @var bool
     */
    protected $allowDelete = true;

    /**
     * 资源url路径
     *
     * @var string
     */
    protected $resource;

    /**
     * 按钮组后面添加一个按钮
     *
     * @param $action
     *
     * @return $this
     */
    public function append($action)
    {
        array_push($this->appends, $action);

        return $this;
    }

    /**
     * 按钮组前面添加一个按钮
     *
     * @param $action
     *
     * @return $this
     */
    public function prepend($action)
    {
        array_unshift($this->prepends, $action);

        return $this;
    }

    /**
     * 禁用删除
     *
     * @return void.
     */
    public function disableDelete()
    {
        $this->allowDelete = false;
    }

    /**
     * 禁用编辑
     *
     * @return void.
     */
    public function disableEdit()
    {
        $this->allowEdit = false;
    }

    /**
     * 设置当前资源的url路径
     *
     * @param $resource
     *
     * @return void
     */
    public function setResource($resource)
    {
        $this->resource = $resource;
    }

    /**
     * 获取资源url路径
     *
     * @return string
     */
    public function getResource()
    {
        return $this->resource ?: parent::getResource();
    }

    /**
     * {@inheritdoc}
     */
    public function display($callback = null)
    {
        if ($callback instanceof \Closure) {
            $callback = $callback->bindTo($this);
            call_user_func($callback, $this);
        }

        $actions = array_merge(['<div class="layui-btn-group">'], $this->prepends);

        if ($this->allowEdit) {
            array_push($actions, $this->editAction());
        }

        if ($this->allowDelete) {
            array_push($actions, $this->deleteAction());
        }

        $actions = array_merge($actions, $this->appends, ['</div>']);

        return implode('', $actions);
    }

    /**
     * 编辑按钮的html代码
     *
     * @return string
     */
    protected function editAction()
    {
        return "<a href='/{$this->getResource()}/{$this->getKey()}/edit' class='layui-btn layui-btn-xs'>编辑</a>";
    }

    /**
     * 删除按钮的html代码
     *
     * @return string
     */
    protected function deleteAction()
    {
        return "<button href='javascript:void(0);' data-resource='/{$this->getResource()}/' data-id='{$this->getKey()}' class='grid-row-delete layui-btn layui-btn-xs layui-btn-danger'>删除</button>";
    }
}